<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 搜索与添加区域 -->
            <div style="margin-top: 15px;">
                <!-- 栅格区域 -->
                <el-row :gutter="20">
                    <el-col :span='7'>
                        <el-input placeholder="请输入内容" v-model="querInfo.query" clearable @clear="getUserList">
                            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                        </el-input>
                    </el-col>
                    <el-col :span='4'>
                        <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
                    </el-col>
                </el-row>
            </div>
            <!-- 表格区域 -->
            <el-table :data="userlist" :border="true" stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="用户名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <!-- 状态开关 -->
                <el-table-column label="状态" width="150px">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <!-- 操作按钮 -->
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <!-- 编辑按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
                        </el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                            @click="removeUserById(scope.row.id)"></el-button>
                        <!-- 上面提示文字 -->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <!-- 分配权限按钮 -->
                            <el-button type="info" icon="el-icon-setting" size="mini" @click="setRole(scope.row)">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="querInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="querInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
            <!-- 添加用户的对话框区域 -->
            <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addFromclose">
                <!-- 内容主题区域 -->
                <el-form ref="addFormRef" label-width="70px" :model="addForm" :rules="addFormRules">
                    <!-- 用户名 -->
                    <el-form-item prop="username" label="用户名">
                        <el-input v-model="addForm.username"></el-input>
                    </el-form-item>
                    <!-- 密码 -->
                    <el-form-item prop="password" label="密码">
                        <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                    <!-- 邮箱 -->
                    <el-form-item prop="email" label="邮箱">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <!-- 手机 -->
                    <el-form-item prop="mobile" label="手机号">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部按钮区域 -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 修改用户的对话框区域 -->
            <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editFormclose">
                <!-- 内容区域 -->
                <el-form ref="editFormRef" label-width="70px" :model="editForm" :rules="editFormRules">
                    <!-- 用户名 -->
                    <el-form-item label="用户名">
                        <el-input v-model="editForm.username" disabled></el-input>
                    </el-form-item>
                    <!-- 邮箱 -->
                    <el-form-item prop="email" label="邮箱">
                        <el-input v-model="editForm.email"></el-input>
                    </el-form-item>
                    <!-- 手机 -->
                    <el-form-item prop="mobile" label="手机号">
                        <el-input v-model="editForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editUser">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配角色对话框区域 -->
            <el-dialog title="分配角色" :visible.sync="setRolesDialogVisible" width="50%" @close="setRolesDialogclose">
                <!-- 内容区域 -->
                <div>
                    <p>当前的用户：{{userInfo.username}}</p>
                    <p>当前的角色：{{userInfo.role_name}}</p>
                    <p>分配新角色：
                        <el-select v-model="selectedRoleId" placeholder="请分配角色">
                            <el-option v-for="item in roleslist" :key="item.id" :label="item.roleName" :value="item.id">
                            </el-option>
                        </el-select>
                    </p>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="setRolesDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
    export default {
        data() {
            //校验邮箱的验证规则
            var checkEmail = (rule, value, cb) => {
                // 验证邮箱的正则
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
                if (regEmail.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法的邮箱'))
            }
            //校验手机号的验证规则
            var checkMobile = (rule, value, cb) => {
                //验证手机号的正则
                const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
                if (regMobile.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法的手机号'))
            }
            return {
                //获取用户列表的请求参数对象
                querInfo: {
                    query: '',
                    //当前的页数
                    pagenum: 1,

                    //当前每页显示多少条数据
                    pagesize: 2
                },
                //用户列表数据
                userlist: [],
                total: 0,
                //控制添加用户的对话框的显示与隐藏
                addDialogVisible: false,
                //控制修改用户的对话框的显示与隐藏
                editDialogVisible: false,
                //控制分配角色的对话框的显示与隐藏
                setRolesDialogVisible: false,
                //添加用户表单数据
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''

                },
                //查询用户信息对象
                editForm: {},
                //添加用户表单验证规则
                addFormRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { validator: checkEmail, trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                },
                //修改用户信息验证规则
                editFormRules: {
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { validator: checkEmail, trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                },
                //当前被分配角色的用户数据对象
                userInfo: {},
                //获取的角色列表数据
                roleslist: [],
                //要分配给用户的角色id值
                selectedRoleId: ''
            };
        },
        created() {
            this.getUserList()
        },
        methods: {
            async getUserList() {
                const { data: res } = await this.$http.get('users', { params: this.querInfo })
                if (res.meta.status !== 200) {
                    return this.$message.error('获取用户列表失败')
                }
                this.userlist = res.data.users
                this.total = res.data.total
            },
            //监听pagesize改变的事件,可以拿到最新的每页显示几行
            handleSizeChange(newsize) {
                this.querInfo.pagesize = newsize
                this.getUserList()
            },
            //监听页面值改变的事件，可以拿到最新的页面数
            handleCurrentChange(newpage) {
                this.querInfo.pagenum = newpage
                this.getUserList()
            },
            //监听switch状态改变，拿到最新的用户信息状态
            async userStateChanged(userInfo) {
                //console.log(userInfo)
                const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
                if (res.meta.status !== 200) {
                    userInfo.mg_state = !userInfo.mg_state
                    return this.$message.error('更新用户状态失败')
                }
                this.$message.success('更新用户状态成功')
            },
            //重置添加用户表单按钮
            addFromclose() {
                this.$refs.addFormRef.resetFields()
            },
            //重置修改用户表单按钮
            editFormclose() {
                this.$refs.editFormRef.resetFields()
            },
            //添加用户按钮方法
            addUser() {
                //对提交的表单数据进行预校验,validate的参数是个布尔值，如果通过校验就是true
                this.$refs.addFormRef.validate(async valid => {
                    //判断是否通过校验
                    if (!valid) return
                    const { data: res } = await this.$http.post('users', this.addForm)
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加用户失败')
                    }
                    this.$message.success('添加用户成功')
                    //隐藏添加用户对话框
                    this.addDialogVisible = false
                    //刷新用户列表
                    this.getUserList()
                })
            },
            //修改用户对话框的显示函数
            async showEditDialog(id) {
                this.editDialogVisible = true
                const { data: res } = await this.$http.get('users/' + id)
                if (res.meta.status !== 200) {
                    return this.$message.error('查询用户信息失败')
                }
                this.editForm = res.data
            },
            //修改用户信息提交按钮
            editUser() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.put('users/' + this.editForm.id, {
                        email: this.editForm.email,
                        mobile: this.editForm.mobile
                    })
                    if (res.meta.status !== 200) {
                        return this.$message.error('更新用户信息失败')
                    }
                    //隐藏修改用户对话框
                    this.editDialogVisible = false
                    //刷新用户列表
                    this.getUserList()
                    //提示修改用户信息成功
                    this.$message.success('更新用户信息成功')
                })
            },
            //根据用户id删除用户信息按钮
            async removeUserById(id) {
                //弹窗询问是否删除,这个弹窗返回一个promise对象,如果点击确定返回值是confirm,点击取消就会返回一个err信息会报错,用catch后返回cancel
                const confirmResult = await this.$confirm('是否要删除该用户', '提示',
                    {
                        confirmButtonText: '确定',
                        type: 'warning',
                        //用catch拦截捕获报错信息并返回，防止vue报错
                    }).catch(err => {
                        return err
                    })
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除')
                }
                const { data: res } = await this.$http.delete('users/' + id)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除用户失败')
                }
                this.$message.success('删除用户成功')
                //刷新用户列表
                this.getUserList()
            },
            //分配权限按钮函数
            async setRole(userInfo) {
                this.userInfo = userInfo
                //在展示对话框之前获取角色列表
                const { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败')
                }
                this.roleslist = res.data
                this.setRolesDialogVisible = true
            },
            //发起修改用户角色的请求
            async saveRoleInfo() {
                //判断是否选择了角色
                if (!this.selectedRoleId) {
                    return this.$message.error('请选择要给用户分配的角色')
                }
                const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
                if (res.meta.status !== 200) {
                    return this.$message.error('分配角色失败')
                }
                this.$message.success('分配角色成功')
                this.getUserList()
                this.setRolesDialogVisible = false
            },
            //监听分配权限对话框的关闭事件
            setRolesDialogclose() {
                this.selectedRoleId = ''
                this.userInfo = {}
            }
        },//方法最外层
    }
</script>